package com.joint.cloud.common.exception;

import com.joint.cloud.common.constants.ResponseCode;
import com.joint.cloud.common.exception.msg.BaseAIOpsExceptionErrorMsg;
import org.springframework.util.StringUtils;

public class AIOpsException extends RuntimeException {

    private final ResponseCode code;

    private final BaseAIOpsExceptionErrorMsg errorMsg;

    public AIOpsException(ResponseCode code) {
        super(code.getMsg());
        this.code = code;
        this.errorMsg = null;
    }

    public AIOpsException(ResponseCode code, BaseAIOpsExceptionErrorMsg errorMsg) {
        super(errorMsg.getErrorMsgLocal());
        this.code = code;
        this.errorMsg = errorMsg;
    }

    public AIOpsException(BaseAIOpsExceptionErrorMsg errorMsg) {
        super(errorMsg.getErrorMsgLocal());
        this.code = ResponseCode.SERVICE_ERROR;
        this.errorMsg = errorMsg;
    }

    public static AIOpsException newInstance(Class<? extends BaseAIOpsExceptionErrorMsg> errorMsgClass) {
        BaseAIOpsExceptionErrorMsg baseAIOpsExceptionErrorMsg = null;
        try {
            baseAIOpsExceptionErrorMsg = errorMsgClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return new AIOpsException(ResponseCode.SERVICE_ERROR, baseAIOpsExceptionErrorMsg);
    }

    public ResponseCode getCode() {
        return code;
    }

    public String getErrorMsg() {
        if (errorMsg != null) {
            if (StringUtils.hasLength(errorMsg.getErrorMsg())) {
                return errorMsg.getErrorMsg();
            } else if (StringUtils.hasLength(errorMsg.getErrorMsgLocal())) {
                return errorMsg.getErrorMsgLocal();
            }
        }
        return null;
    }

    public String getErrorMsgLocal() {
        if (errorMsg != null) {
            if (StringUtils.hasLength(errorMsg.getErrorMsgLocal())) {
                return errorMsg.getErrorMsgLocal();
            } else if (StringUtils.hasLength(errorMsg.getErrorMsg())) {
                return errorMsg.getErrorMsg();
            }
        }
        return null;
    }
}
